﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Users_Create : BaseUserPage
{
    public override Acms.Bll.Role.Roles[] AllowedRoles
    {
        get { return new[] { Acms.Bll.Role.Roles.Developer, Acms.Bll.Role.Roles.MembershipAdministrator }; }
    }

    public override void GetBreadCrumbs(BaseMasterPage.BreadCrumbCollection breadcrumbs)
    {
        base.GetBreadCrumbs(breadcrumbs);
        breadcrumbs.Add("Create New User");
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void dsUser_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.User> e)
    {
        e.SetData(Acms.Bll.User.CreateInstance(this.AcmsContext.SiteId));
    }

    protected void dsUser_UpdateData(object sender, Acms.DataControls.UpdateDataEventArgs<Acms.Bll.User> e)
    {
        try
        {
            e.Item.BeginTransaction();
            e.Item.ResetPassword();
            e.Item.Update(true);

            CheckBoxList roles = (CheckBoxList)fvUser.FindControl("cblRoles");

            foreach (ListItem item in roles.Items)
            {
                if (item.Selected)
                {
                    var role = Acms.Bll.UserRole.CreateInstance(e.Item.Id, (Acms.Bll.Role.Roles)int.Parse(item.Value), AcmsContext.SiteId);
                    role.Start = DateTime.Now;
                    role.UseTransaction(e.Item.TransactionKey);
                    role.Update();
                }
            }
            e.Item.CommitTransaction();
        }
        catch
        {
            e.Item.RollbackTransaction();
            throw;
        }
        Response.Redirect("~/Users/Default.aspx");
    }

    protected void dsRoles_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.Role> e)
    {
        e.SetData(Acms.Bll.Role.GetAllBySiteId(this.AcmsContext.SiteId));
    }

    protected void valUserNameUnique_Validate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = Acms.Bll.User.GetByUserName(args.Value, AcmsContext.SiteId) == null;
    }

    protected void valEmailUnique_Validate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = Acms.Bll.User.GetByEmailAddress(args.Value, AcmsContext.SiteId) == null;
    }

}
